import { BeforeInsert, Column, Entity, PrimaryGeneratedColumn } from 'typeorm'
import { Exclude } from 'class-transformer'

import * as bcrypt from 'bcryptjs'

@Entity('user')
export class User {
  @PrimaryGeneratedColumn('uuid')
  id: number

  @Column({ comment: '用户名', length: 100 })
  username: string

  @Column({ comment: '昵称', length: 100, default: '' })
  nickname: string

  // @Column({ comment: '密码', select: false })
  // 通过序列化工具实现对 password字段的过滤-保证响应体不返回这个 字段
  @Exclude()
  @Column({ comment: '密码' })
  password: string

  @Column({ comment: '头像', default: '' })
  avatar: string

  @Column('simple-enum', {
    enum: ['root', 'author', 'visitor'],
    comment: '用户角色'
  })
  role: string

  @Column({
    type: 'timestamp',
    // 在数据库里面列名就是 create_time, 而不是 createTime
    name: 'create_time',
    default: () => 'CURRENT_TIMESTAMP',
    comment: '创建时间'
  })
  createTime: Date

  @Column({
    type: 'timestamp',
    name: 'update_time',
    default: () => 'CURRENT_TIMESTAMP',
    comment: '更新时间'
  })
  updateTime: Date

  // 装饰器@BeforeInsert来装饰encryptPwd方法，表示该方法在数据插入之前调用，这样就能保证插入数据库的密码都是加密后的。
  @BeforeInsert()
  async encryptPwd() {
    this.password = await bcrypt.hashSync(this.password)
  }
}
